package henu.graduation_design.onlineshop;

import henu.graduation_design.tool.AnalyseProductAppraiseJson;
import henu.graduation_design.tool.AnalyseProductInfoJson;
import henu.graduation_design.util.AsyncImageLoader;
import henu.graduation_design.util.JsonLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ProductInfoActivity extends Activity {

	TextView nameTextView, name1TextView, name2TextView;
	TextView priceTextView;
	TextView originalPriceTextView;
	TextView categoryTextView;
	TextView introTextView;
	ImageView imageView;
	TextView time1TextView, time2TextView;
	TextView comment1TextView, comment2TextView;
	TextView moreTextView;
	ImageView backImageView, buyImageView;

	String productID;
	Animation rotateAnimation = null;
	SharedPreferences sp;

	private JsonLoader jsonLoader = new JsonLoader();
	private AsyncImageLoader asyncImageLoader = new AsyncImageLoader();
	List<HashMap<String, Object>> list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_product_info);

		nameTextView = (TextView) findViewById(R.id.product_info_name);
		priceTextView = (TextView) findViewById(R.id.product_info_price);
		originalPriceTextView = (TextView) findViewById(R.id.product_info_original_price);
		categoryTextView = (TextView) findViewById(R.id.product_info_category);
		introTextView = (TextView) findViewById(R.id.product_info_intro);
		imageView = (ImageView) findViewById(R.id.product_info_image);
		name1TextView = (TextView) findViewById(R.id.name1TextView);
		name2TextView = (TextView) findViewById(R.id.name2TextView);
		comment1TextView = (TextView) findViewById(R.id.comment1TextView);
		comment2TextView = (TextView) findViewById(R.id.comment2TextView);
		time1TextView = (TextView) findViewById(R.id.time1TextView);
		time2TextView = (TextView) findViewById(R.id.time2TextView);
		moreTextView = (TextView) findViewById(R.id.product_info_more);
		backImageView = (ImageView) findViewById(R.id.page_back);
		buyImageView = (ImageView) findViewById(R.id.buy_image);
		list = new ArrayList<HashMap<String, Object>>();
		rotateAnimation = AnimationUtils.loadAnimation(this,
				R.anim.image_rotate);

		Intent intent = getIntent();// 获得传过来的Intent。
		productID = intent.getStringExtra("ID");// 根据键name取出值。

		try {
			String urlString = getString(R.string.url_productinfo) + "?id="
					+ productID;
			loadInfoJson(urlString);
			String urlString2 = getString(R.string.url_product_appraise)
					+ "?id=" + productID + "&tag=-1";
			loadAppraiseJson(urlString2);
		} catch (Exception e) {
			e.printStackTrace();
		}

		backImageView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		buyImageView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				buyImageView.startAnimation(rotateAnimation);
				sp = getSharedPreferences("SP", MODE_PRIVATE);
				if (!sp.getBoolean("IsLogin", false)) {
					Intent intent = new Intent(ProductInfoActivity.this,
							LoginDialogActivity.class);
					startActivityForResult(intent, 0);
				} else {
					// 购物车添加商品
					addProductToCart();
				}
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case RESULT_OK:
			boolean login = data.getBooleanExtra("isLogin", false);
			if (login) {
				// 购物车添加商品
				addProductToCart();
			}
			else {
				rotateAnimation.cancel();
			}
			break;

		default:
			break;
		}
	}

	private void addProductToCart() {
		sp = getSharedPreferences("SP", MODE_PRIVATE);
		try {
			Map<String,Object> jsonObject = new HashMap<String, Object>();
			jsonObject.put("productID", productID);
			loadJson(getString(R.string.url_add_product_to_cart),
					sp,
					jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void loadInfoJson(final String url) {
		jsonLoader.getJsonObject(url, new JsonLoader.JsonObjectCallback() {
			public void jsonLoaded(JSONObject jsonObject) {
				HashMap<String, Object> hashMap = new HashMap<String, Object>();
				AnalyseProductInfoJson analyse = new AnalyseProductInfoJson(
						jsonObject);
				try {
					hashMap = analyse.getProduct();
				} catch (JSONException e) {
					Toast.makeText(getApplicationContext(),
							"解析category的json数据发生异常", Toast.LENGTH_LONG).show();
				}
				nameTextView.setText(hashMap.get("name").toString());
				if (hashMap.get("price").toString()
						.equals(hashMap.get("originalPrice").toString())) {
					priceTextView.setText("价格：￥"
							+ hashMap.get("price").toString());
					originalPriceTextView.setText("");
				} else {
					priceTextView.setText("特价：￥"
							+ hashMap.get("price").toString());
					originalPriceTextView.setText("原价：￥"
							+ hashMap.get("originalPrice").toString());
					originalPriceTextView.getPaint().setFlags(
							Paint.STRIKE_THRU_TEXT_FLAG);
				}

				categoryTextView.setText("分类："
						+ hashMap.get("category").toString());
				introTextView.setText(hashMap.get("intro").toString());
				loadImage(hashMap.get("imageUri").toString(), imageView);
			}
		});
	}

	private void loadImage(final String url, final ImageView imageView) {
		// 如果缓存过就会从缓存中取出图像，ImageCallback接口中方法也不会被执行
		Drawable cacheImage = asyncImageLoader.loadDrawable(url,
				new AsyncImageLoader.ImageCallback() {
					// 请参见实现：如果第一次加载url时下面方法会执行
					public void imageLoaded(Drawable imageDrawable) {
						imageView.setImageDrawable(imageDrawable);
					}
				});
		if (cacheImage != null) {
			imageView.setImageDrawable(cacheImage);
		}
	}

	private void loadAppraiseJson(final String url) {
		jsonLoader.getJsonArray(url, new JsonLoader.JsonArrayCallback() {
			public void jsonLoaded(JSONArray jsonArray) {
				list.clear();
				AnalyseProductAppraiseJson analyse = new AnalyseProductAppraiseJson(
						jsonArray);
				try {
					list = analyse.getList();
				} catch (JSONException e) {
					Toast.makeText(getApplicationContext(),
							"解析category的json数据发生异常", Toast.LENGTH_LONG).show();
				}
				if (list.size() != 0) {
					moreTextView.setText("加载更多>>");
					if (list.size() == 1) {
						name1TextView.setText(list.get(0).get("name")
								.toString());
						time1TextView.setText(list.get(0).get("time")
								.toString());
						comment1TextView.setText(list.get(0).get("comment")
								.toString());
					} else {
						name1TextView.setText(list.get(0).get("name")
								.toString());
						time1TextView.setText(list.get(0).get("time")
								.toString());
						comment1TextView.setText(list.get(0).get("comment")
								.toString());
						name2TextView.setText(list.get(1).get("name")
								.toString());
						time2TextView.setText(list.get(1).get("time")
								.toString());
						comment2TextView.setText(list.get(1).get("comment")
								.toString());
					}

					moreTextView.setOnClickListener(new OnClickListener() {
						public void onClick(View v) {
							moreTextView.setTextColor(Color.RED);
							Intent intent = new Intent(
									ProductInfoActivity.this,
									AppraiseActivity.class);
							intent.putExtra("ID", productID);
							startActivity(intent);
						}
					});
				} else {
					moreTextView.setText("当前不存在评论");
				}
			}
		});
	}

	private void loadJson(final String url, SharedPreferences spp,
			final Map<String,Object> mapEntry) {
		jsonLoader.postJson(url, spp, mapEntry,
				new JsonLoader.JsonObjectCallback() {
					public void jsonLoaded(JSONObject jsonObject) {
						boolean result = false;
						try {
							result = jsonObject
									.getBoolean("AddProductToCartResult");
						} catch (JSONException e) {
							e.printStackTrace();
						}
						if (result) {
							Toast.makeText(getApplicationContext(),
									"商品已添加进购物车", Toast.LENGTH_LONG).show();
							rotateAnimation.cancel();
						} else {
							Toast.makeText(getApplicationContext(), "添加失败",
									Toast.LENGTH_LONG).show();
						}
					}
				});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_product_info, menu);
		return true;
	}

}
